package com.joe.demo.chat.protocol;

import com.joe.demo.chat.config.Config;
import com.joe.demo.chat.message.LoginRequestMessage;
import com.joe.demo.chat.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-09-03
 */
public class TestSerializer {

    public static void main(String[] args) {
        final MessageCodecSharable messageCodecSharable = new MessageCodecSharable();
        LoggingHandler loggingHandler = new LoggingHandler();
        final EmbeddedChannel embeddedChannel = new EmbeddedChannel(loggingHandler, messageCodecSharable, loggingHandler);

        final LoginRequestMessage loginRequestMessage = new LoginRequestMessage("zhangsan", "123", null);

        // embeddedChannel.writeOutbound(loginRequestMessage);

        final ByteBuf byteBuf = messageToByteBuf(loginRequestMessage);
        embeddedChannel.writeInbound(byteBuf);
    }


    public static ByteBuf messageToByteBuf(Message msg) {
        int algorithm = Config.getSerializerAlgorithm().ordinal();
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        out.writeBytes(new byte[]{1, 2, 3, 4});
        out.writeByte(1);
        out.writeByte(algorithm);
        out.writeByte(msg.getMessageType());
        out.writeInt(msg.getSequenceId());
        out.writeByte(0xff);
        byte[] bytes = Serializer.Algorithm.values()[algorithm].serializer(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
        return out;
    }
}
